//
//  WJImageAutoSizeDemo2Controller.m
//  JerryIos
//
//  Created by 王军 on 2018/2/14.
//  Copyright © 2018年 王军. All rights reserved.
//

#import "WJIASDemo2Controller.h"
#import "WJIASData1.h"
#import "WJIASNews.h"
#import "MJExtension.h"
#import "XHWebImageAutoSize.h"
#import "WJIASDemo2Cell.h"

@interface WJIASDemo2Controller ()

@property(nonatomic,strong) NSArray *itemArray;

@end

static NSString *const cellId = @"WJIASDemo2Cell";

@implementation WJIASDemo2Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
    
}

-(NSArray *)itemArray {
    if (_itemArray == nil) {
        NSString *json = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"]
                                                   encoding:NSUTF8StringEncoding
                                                      error:nil];
        WJIASData1 *iasData = [WJIASData1 mj_objectWithKeyValues:json];
        NSMutableArray *mutItemArray = [NSMutableArray array];
        for (NSDictionary *dic in iasData.data) {
            WJIASNews *news = [WJIASNews newsWithDict:dic];
            [mutItemArray addObject:news];
        }
        _itemArray = mutItemArray;
    }
    return _itemArray;
}

#pragma mark-tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    WJIASNews *news = self.itemArray[indexPath.row];
    /**
     *  参数1:图片URL
     *  参数2:imageView 宽度
     *  参数3:预估高度,(此高度仅在图片尚未加载出来前起作用,不影响真实高度)
     */
    CGFloat imageHeight = [XHWebImageAutoSize imageHeightForURL:[NSURL URLWithString:news.top_image] layoutWidth:[UIScreen mainScreen].bounds.size.width-16 estimateHeight:200];
    //cell高度 = 上间隙8+image高度+文字高度60+下间隙8
    return 8+imageHeight+60+8;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WJIASDemo2Cell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell = [[WJIASDemo2Cell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    WJIASNews *news = self.itemArray[indexPath.row];
    cell.titleView.text = news.title;
    cell.sourceView.text = [NSString stringWithFormat:@"来源:%@",news.source];
    cell.countView.text = [NSString stringWithFormat:@"回复:%ld",news.reply_count];
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:news.top_image] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        /**  缓存image size */
        [XHWebImageAutoSize storeImageSize:image forURL:imageURL completed:^(BOOL result) {
            /** reload */
            if(result)  [tableView xh_reloadDataForURL:imageURL];
        }];
        
    }];
    return cell;
}




@end
